package com.wd.common.utils

import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import retrofit2.create
import java.util.concurrent.TimeUnit

/**
 * 作者：马海钊
 * 时间：2024/5/23 9:39
 * 功能：
 */
class RetrofitConfig private constructor(){

    private var BASE_URL="http://10.59.9.18/"
    companion object{
        private var instance: RetrofitConfig?=null
        fun getInstance(): RetrofitConfig {
            return instance ?: synchronized(this){
                RetrofitConfig().also { instance =it }
            }
        }
    }
    fun<T>provideApi(service:Class<T>):T{
        return provideRetrofit(provideOkhttpClient()).create(service)
    }

    //配置okHttp
    private fun provideOkhttpClient():OkHttpClient{
        val loggingInterceptor=HttpLoggingInterceptor{
            Log.d("httplog",it)
        }
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)

        return OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .retryOnConnectionFailure(true)//失败重试
            .connectTimeout(1,TimeUnit.SECONDS)
            .readTimeout(1,TimeUnit.SECONDS)
            .writeTimeout(1,TimeUnit.SECONDS)
            .build()

    }
        private fun provideRetrofit(okHttpClient: OkHttpClient):Retrofit{
            return Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .build()
        }


}